// pages/addressList/editAddress/index.js
import Http from '../../../utils/http.js';
import { isEmpty } from '../../../utils/util.js';
import { isvalidPhone } from '../../../utils/validate.js';
let app = getApp();
var prevPage;//前一页
var preverPage;//再前一页

Page({

  /**
   * 页面的初始数据
   */
  data: {
    attrInfo:{},
    type:'',//编辑或者新增
    canAddrChoose:'',//是否可以选择
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      attrInfo: JSON.parse(options.attrInfo),
      type: options.type,
      canAddrChoose: options.canAddrChoose
    })
    wx.setNavigationBarTitle({
      title: options.type==='eidt'?"编辑地址":"新增地址"
    })
  },
  bindRegionChange(e){
    const valueList = e.detail.value;
    this.setData({
      'attrInfo.province': valueList[0],
      'attrInfo.city': valueList[1],
      'attrInfo.district': valueList[2]
    })
  },
  bindKeyInput(e) {
    const value = e.detail.value;
    const key = e.target.dataset.key;
    const targetVal = `attrInfo.${key}`
    this.setData({
      [targetVal]: value
    })
  },
  switch1Change(e) {
    this.setData({
      'attrInfo.isDefaultAddress': e.detail.value
    })
  },
  handleSave(){
    if (isEmpty(this.data.attrInfo.receiveName)){
      wx.showToast({
        title: '请填写收货人姓名',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (isEmpty(this.data.attrInfo.receivePhone)) {
      wx.showToast({
        title: '请填写收货人手机号',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    } 
    if (!isvalidPhone(this.data.attrInfo.receivePhone)) {
      wx.showToast({
        title: '收货人手机号填写有误',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (isEmpty(this.data.attrInfo.province)) {
      wx.showToast({
        title: '请选择收货人地区',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    if (isEmpty(this.data.attrInfo.receiveAddress)) {
      wx.showToast({
        title: '请填写收货人详细地址',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    const data = {
      city: this.data.attrInfo.city,
      district: this.data.attrInfo.district,
      province: this.data.attrInfo.province,
      receiveAddress: this.data.attrInfo.receiveAddress,
      receiveName: this.data.attrInfo.receiveName,
      receivePhone: this.data.attrInfo.receivePhone,
    }
    if(this.data.type==='edit'){
      Http.Request('PUT', `/api/customer/receiveAddress/receiveAddress/${this.data.attrInfo.bizid}/${this.data.attrInfo.isDefaultAddress ? 'DEFAULT' : 'NOT_DEFAULT'}/v1`, data).then(res=>{
        let addrIndex = prevPage.data.addrList.findIndex(o=>{
          return o.bizid === this.data.attrInfo.bizid
        });
        prevPage.data.addrList[addrIndex] = res;
        prevPage.setData({
          addrList: prevPage.data.addrList,
          currentBizid: res.bizid
        })
        //如果前一页的canAddrChoose为true则是实物订单选择地址进来的,需要更新创建订单页面的数据
        if (prevPage.data.canAddrChoose == '1'){
          preverPage.setData({
            addrBizid:res.bizid,
            receiveName: res.receiveName,
            receivePhone: res.receivePhone,
            currentAddress: res.province + res.city + res.district + res.receiveAddress
          })
        }
        wx.showToast({
          title: '编辑地址成功',
          icon: "success",
          duration: app.globalData.duration,
          success: () => {
            setTimeout(()=>{
              wx.navigateBack({
                delta: prevPage.data.canAddrChoose=='1'?2:1
              })
            }, app.globalData.duration)
          }
        })
      }).catch(err=>{
        wx.showToast({
          title: err,
          icon: "none",
          duration: app.globalData.duration
        })
      })
    }else{
      Http.Request('POST', `/api/customer/receiveAddress/receiveAddress/${this.data.attrInfo.isDefaultAddress ? 'DEFAULT' : 'NOT_DEFAULT'}/v1`, data).then(res=>{
        prevPage.setData({
          addrList: prevPage.data.addrList.push(res),
          currentBizid:res.bizid
        })
        //如果前一页的canAddrChoose为true则是实物订单选择地址进来的,需要更新创建订单页面的数据
        if (prevPage.data.canAddrChoose) {
          preverPage.setData({
            addrBizid: res.bizid,
            receiveName: res.receiveName,
            receivePhone: res.receivePhone,
            currentAddress: res.province + res.city + res.district + res.receiveAddress
          })
        }
        wx.showToast({
          title: '新增地址成功',
          icon: "success",
          duration: app.globalData.duration,
          success: () => {
            setTimeout(() => {
              wx.navigateBack({
                delta: prevPage.data.canAddrChoose ? 2 : 1
              })
            }, app.globalData.duration)
          }
        })
      }).catch(err => {
        wx.showToast({
          title: err,
          icon: "none",
          duration: app.globalData.duration
        })
      })
    }
  },
  delAddr(){
    Http.Request('DELETE', `/api/customer/receiveAddress/deleteReceiveAddressByBizId/${this.data.attrInfo.bizid}/v1`).then(res=>{
      let addrIndex = prevPage.data.addrList.findIndex(o => {
        return o.bizid === this.data.attrInfo.bizid
      });
      prevPage.data.addrList.splice(addrIndex,1)
      prevPage.setData({
        addrList: prevPage.data.addrList
      })
      wx.showToast({
        title: '删除地址成功',
        icon: "success",
        duration: app.globalData.duration,
        success: () => {
          setTimeout(() => {
            wx.navigateBack({
              delta:1
            })
          }, app.globalData.duration)
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var pages = getCurrentPages();
    prevPage = pages[pages.length - 2];
    preverPage = pages[pages.length - 3];
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})